import {
  reqGoodsInfo,
  reqAddOrUpdateCount
} from '../../api/index';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showAction: false, //是否展示遮罩层
    currentItem: '', //加入购物车与立即购买
    goodsId: '', //商品ID
    goodsInfo: {},
    count: 1, //商品数量
    blessing: '祝福语'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    options.goodsId && this.setData({
      goodsId: options.goodsId
    });
    this.getGoodsInfo();
  },
  //加入购物车
  addCart() {
    this.setData({
      showAction: true,
      currentItem: 'cart'
    })
  },
  //点击黑色区域
  onClose() {
    this.setData({
      showAction: false,
      currentItem: ''

    })
  },
  //立即购买
  buy() {
    this.setData({
      showAction: true,
      currentItem: 'buy'
    })
  },
  //确定按钮
  confirm() {
    //判断加入购物车
    if (this.data.currentItem == 'cart') {
      this.addGoodsCart()
    } else {
       const {blessing} = this.data;
       if(!blessing){
         wx.showToast({
            title:'务必输入祝福语'
         })
         return;
       }
       this.goOrderDetail();
    }
  },
  //获取商品详情
  async getGoodsInfo() {
    let result = await reqGoodsInfo(this.data.goodsId);
    if (result.code == 200) {
      this.setData({
        goodsInfo: result.data
      })
    }
  },
  async addGoodsCart() {
    const {
      count,
      blessing,
      goodsId
    } = this.data;
    try {
      await reqAddOrUpdateCount({
        count,
        goodsId,
        blessing
      });
      wx.showToast({
        title: '加入购物车成功',
      });
      this.setData({
         currentItem:'',
         showAction:false
      })
    } catch (error) {

    }
  },
  handleChangeCount(e){

     this.setData({
       count:e.detail
     })
  },
  goOrderDetail(){
    wx.navigateTo({
      url: `/pages/order-detail/index?goodsId=${this.data.goodsId}&blessing=${this.data.blessing}`,
    })
  }
})